package com.example.zzx.dovebook.login.ui;

import android.text.TextUtils;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.example.baselibrary.LoadCallback;
import com.example.baselibrary.net.HttpUtil;
import com.example.zzx.dovebook.base.BaseViewModel;
import com.example.zzx.dovebook.user.model.User;

import java.util.Map;

public class LoginViewModel extends BaseViewModel<LoginRepository> {

    private String[] mLoginKeys = new String[] {
            "userName",
            "userPassword"
    };

    private String[] mLoginTips = new String[] {
            "用户名不能为空",
            "密码不能为空",
    };

    private String[] mSignUpKeys = mLoginKeys;
    private String[] mSignUpTips = mLoginTips;

    public LoginViewModel(LoginRepository reponsity) {
        super(reponsity);
    }


    public LiveData<User> login(String userName, String userPassword) {
        MutableLiveData<User> result = new MutableLiveData<>();
        String errorMessage = HttpUtil.checkParams(mLoginTips, userName, userPassword);
        if (!TextUtils.isEmpty(errorMessage)) {
            setErrorMessage(errorMessage);
            return result;
        }
        Map<String, String> paraMap = HttpUtil.wrapParams(mLoginKeys,
                userName, userPassword);
        getRepository().login(paraMap, new LoadCallback<User>() {
            @Override
            public void loadSuccess(User data) {
                result.postValue(data);
            }

            @Override
            public void loadFailed(String errorMessage) {
                postErrorMessage(errorMessage);
            }

            @Override
            public void loadNull(String message) {

            }
        });
        return result;
    }

    public LiveData<User> signUp(String userName, String password) {
        MutableLiveData<User> result = new MutableLiveData<>();
        String errorMessage = HttpUtil.checkParams(mSignUpTips, userName, password);
        if (!TextUtils.isEmpty(errorMessage)) {
            setErrorMessage(errorMessage);
            return result;
        }
        Map<String, String> paraMap = HttpUtil.wrapParams(mSignUpKeys,
                userName, password);
        getRepository().signUp(paraMap, new LoadCallback<User>() {
            @Override
            public void loadSuccess(User data) {
                result.postValue(data);
            }

            @Override
            public void loadFailed(String errorMessage) {
                postErrorMessage(errorMessage);
            }

            @Override
            public void loadNull(String message) {

            }
        });
        return result;
    }
}
